package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.ShopCarAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.CartBean;
import com.weixin.paleituo.bean.FailureBean;
import com.weixin.paleituo.bean.ModifyShopCartNumberBean;
import com.weixin.paleituo.bean.NofailureBean;
import com.weixin.paleituo.bean.OrderGoods;
import com.weixin.paleituo.bean.ShopCarBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.ShopCartChildCheckEvent;
import com.weixin.paleituo.eventbus.ShopCartDeleteEvent;
import com.weixin.paleituo.eventbus.ShopCartGropCheckEvent;
import com.weixin.paleituo.eventbus.ShopCartNumberEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 购物车
 */
public class ShopCarActivity extends BasePersonActivity implements View.OnLayoutChangeListener {
    @BindView(R.id.tv_retry_activity_shop_car)
    TextView mTvRetryActivityShopCar;
    @BindView(R.id.ll_no_data_activity_shop_car)
    LinearLayout mLlNoDataActivityShopCar;
    @BindView(R.id.expandable_listview_activity_shop_car)
    ExpandableListView mExpandableListviewActivityShopCar;
    @BindView(R.id.cb_all_select_activity_shop_car)
    CheckBox mCbAllSelectActivityShopCar;
    @BindView(R.id.tv_money_activity_shop_car)
    TextView mTvMoneyActivityShopCar;
    @BindView(R.id.tv_goaccount_activity_shop_car)
    TextView mTvGoaccountActivityShopCar;
    @BindView(R.id.ll_data_root_acticity_shop_car)
    LinearLayout mLlDataRootActicityShopCar;
    private LoadingPagerHead mLoadingPagerHead;
    List<NofailureBean> mNofailureBeanList = new ArrayList<>();
    private ShopCarAdapter mShopCarAdapter;
    @BindView(R.id.ll_root_activity_baseperson)
    LinearLayout mLinearLayoutRoot;
    private boolean isSoftshow = false;
    private boolean isAllSelect = false;
    private    View  footview;
    private boolean isFirst=true;


    /*    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_shop_car);
            ButterKnife.bind(this);
        }*/
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    private Dialog mLoadingDialog;
    private List<FailureBean> mFailureBeans;
    @BindView(R.id.rl_allselect_activity_shop)
    RelativeLayout mRlAllSelect;

    @Override
    protected View getContentView(Context context) {

        mLoadingPagerHead = new LoadingPagerHead(this) {
            @Override
            protected void close() {
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(ShopCarActivity.this, R.layout.activity_shop_car);
            }

            @Override
            protected void reLoading() {
                retry();

            }
        };
        footview = UIUtils.inflate(ShopCarActivity.this, R.layout.foot_layout_shop_cart);
        return mLoadingPagerHead;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLoadingPagerHead.showPagerView(Contans.STATE_LOADING);
        retry();
    }

    /**
     * 重新加载
     */
    private void retry() {

        Observable<StatusCode<ShopCarBean>> getshopCarDataObservable = ApiUtils.getApi().getshopCarData(BaseApplication.getUserId());

        HttpUtil.getInstance().toSubscribe(getshopCarDataObservable, new ProgressSubscriber<ShopCarBean>(this) {
            @Override
            protected void _onNext(StatusCode<ShopCarBean> shopCarBeanStatusCode) {
                mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                ShopCarBean shopCarBean = shopCarBeanStatusCode.getData();
                mFailureBeans = shopCarBean.getFailure();
                mTvGoaccountActivityShopCar.setText("去结算");

                List<NofailureBean> nofailureBeans = shopCarBean.getNofailure();
                if ((mFailureBeans == null || mFailureBeans.size() == 0) && (nofailureBeans == null || nofailureBeans.size() == 0)) {
                    //没数据
                    mLlNoDataActivityShopCar.setVisibility(View.VISIBLE);
                    mLlDataRootActicityShopCar.setVisibility(View.GONE);   //没数据
                } else {
                    mLlNoDataActivityShopCar.setVisibility(View.GONE);
                    mLlDataRootActicityShopCar.setVisibility(View.VISIBLE);
                    //有数据
                    if (nofailureBeans != null && nofailureBeans.size() > 0) {
                        //购物车数据
                        mNofailureBeanList.clear();
                        mNofailureBeanList.addAll(nofailureBeans);
                        mShopCarAdapter.notifyDataSetChanged();
                        if (isFirst){
                        explandableListviewShowAll();
                        isFirst=false;
                        }
                        mTvMoneyActivityShopCar.setText("￥" + UIUtils.getMoney(caculateSumPrice()));
                        setSelectAllState();
                     //   mTvTitle.setText("购物车(" + calulateShopNumber() + ")");
                    }else {
                        mNofailureBeanList.clear();
                        mShopCarAdapter.notifyDataSetChanged();
                        setSelectAllState();
                    }
                    if (mFailureBeans !=null && mFailureBeans.size()>0){
                        //失效
                      //  item_failure_foot_layout.xml
                       // foot_layout_shop_cart.xml

                       LinearLayout mLinearLayoutcontent=footview.findViewById(R.id.ll_failure_content_root_foot_layout_shop_cart);
               TextView tvFailureNumber=        footview.findViewById(R.id.tv_failure_number_foot_layout_shop_cart);
               tvFailureNumber.setText("失效宝贝"+ mFailureBeans.size()+"件");

                TextView tvDelect=       footview.findViewById(R.id.tv_delect_all_foot_layout_shop_cart);

                        tvDelect.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //删除

                                deleteFailure(mFailureBeans);
                            }
                        });

                   for (FailureBean failureBean: mFailureBeans){
                       View    failureItemView=   UIUtils.inflate(ShopCarActivity.this,R.layout.item_failure_foot_layout);
                     ImageView imageView= failureItemView.findViewById(R.id.iv_icon_item_failure_foot_layout);
                  TextView tvGoodsName=     failureItemView.findViewById(R.id.tv_goodsname_item_failure_foot_layout);
                 TextView tvSelectAttr=      failureItemView.findViewById(R.id.select_attr_item_failure_foot_layout);
                       Glide.with(ShopCarActivity.this).load(failureBean.getGoodsimage()).into(imageView);
                 tvGoodsName.setText(failureBean.getGoodsname()+"");
                 tvSelectAttr.setText(failureBean.getSpec_info()+"");

                       mLinearLayoutcontent.addView(failureItemView);
                   }
                        mExpandableListviewActivityShopCar.addFooterView(footview);

                    }


                }


            }

            @Override
            protected void _onError(String message) {

                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                ToastUtils.makeText(message);

            }
        }, "", lifecycleSubject, false, true);

    }

    /**
     * 删除失效订单
     * @param failureBeans
     */
    private void deleteFailure(List<FailureBean> failureBeans) {
        String cartIc="";
        for (FailureBean failureBean:failureBeans){
            cartIc=cartIc+failureBean.getCartId()+",";
        }

        Observable observable = ApiUtils.getApi().deleteShopCart(cartIc).compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {

                if (mLoadingDialog == null) {

                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(ShopCarActivity.this, "");
                }
                LoadingDialogUtils.show(mLoadingDialog);

            }
        }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<String>(this) {
            @Override
            protected void _onNext(StatusCode statusCode) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);


                mExpandableListviewActivityShopCar.removeFooterView(footview);
                if (mNofailureBeanList.size()==0 &&(mFailureBeans==null || mFailureBeans.size()==0)){

                    mLlNoDataActivityShopCar.setVisibility(View.VISIBLE);
                    mLlDataRootActicityShopCar.setVisibility(View.GONE);
                    //没数据

                }

            }

            @Override
            protected void _onError(String message) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);


                ToastUtils.makeText(message);

            }


        },"",lifecycleSubject,false,true);

    }

    /**
     * 全部展开
     */
    private void explandableListviewShowAll() {
        int groupCount = mExpandableListviewActivityShopCar.getCount();
        for (int i = 0; i < groupCount; i++) {
            mExpandableListviewActivityShopCar.expandGroup(i);

        }
    }
    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;

        mLinearLayoutRoot.addOnLayoutChangeListener(this);
        mShopCarAdapter = new ShopCarAdapter(this, mNofailureBeanList);
        mExpandableListviewActivityShopCar.setAdapter(mShopCarAdapter);
        //遍历所有group,将所有项设置成默认展开
        mTvTitle.setText("购物车");
        mTvGoaccountActivityShopCar.setText("去结算");

        //    retry();
        mCbAllSelectActivityShopCar.setBackgroundResource(R.mipmap.xe_h);
    }

    @OnClick(R.id.tv_goaccount_activity_shop_car)
    public void onMTvGoaccountActivityShopCarClicked() {
        ArrayList<OrderGoods> orderGoodsList=new ArrayList<>();
        orderGoodsList.clear();
                for(NofailureBean nofailureBean:mNofailureBeanList){
                    List<CartBean> cart = nofailureBean.getCart();
                    for (CartBean cartBean:cart){
                        if (cartBean.isIscheck()){
                            OrderGoods orderGoods=new OrderGoods();
                            orderGoods.setGoodsName(cartBean.getGoodsname());
                            orderGoods.setCount(cartBean.getCount());
                            orderGoods.setId(cartBean.getGoodsId());
                            orderGoods.setListUrl(cartBean.getGoodsimage());
                            orderGoods.setStoreId(Integer.valueOf(nofailureBean.getStoreId()));
                            orderGoods.setPrice(Double.toString(cartBean.getPrice()));
                            orderGoods.setVip(cartBean.getDisprice()>0?true:false);
                            orderGoods.setSpecialSales(cartBean.getDisprice()+"");
                            orderGoods.setCouponMoney(cartBean.getCoupon());
                            orderGoods.setGoodsSpecsInfo(cartBean.getSpec_info());
                            orderGoods.setIdlist(cartBean.getIdlist());
                            orderGoodsList.add(orderGoods);
                        }
                    }

                }
                if (orderGoodsList.size()>0){
                    Intent intent = CreateOrderActivity.call2CreateOrder(this, "",orderGoodsList );
                    startActivity(intent);
                }else {
                    ToastUtils.makeText("您还没有选择商品哦");
                }

    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, ShopCarActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void initEvent() {
        super.initEvent();
        mRlAllSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAllSelect) {
                    isAllSelect = false;
                    mCbAllSelectActivityShopCar.setBackgroundResource(R.mipmap.xe_h);
                    for (NofailureBean nofailureBean : mNofailureBeanList) {
                        for (CartBean cartBean : nofailureBean.getCart()) {

                            cartBean.setIscheck(false);
                        }
                        nofailureBean.setCheck(false);
                    }
                    mTvGoaccountActivityShopCar.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
                    mTvMoneyActivityShopCar.setText("￥" + UIUtils.getMoney(caculateSumPrice()));
                    mShopCarAdapter.notifyDataSetChanged();
                } else {
                    isAllSelect = true;
                    mCbAllSelectActivityShopCar.setBackgroundResource(R.mipmap.chooce_green);
                    for (NofailureBean nofailureBean : mNofailureBeanList) {
                        for (CartBean cartBean : nofailureBean.getCart()) {
                            cartBean.setIscheck(true);
                        }
                        nofailureBean.setCheck(true);
                    }
                    mTvMoneyActivityShopCar.setText("￥" + UIUtils.getMoney(caculateSumPrice()));
                    mTvGoaccountActivityShopCar.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
                    mShopCarAdapter.notifyDataSetChanged();

                }
            }
        });




        mTvRetryActivityShopCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MainActivity.goGoodsShop(ShopCarActivity.this,1);


            }
        });
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {

            //  Toast.makeText(MainActivity.this, 监听到软键盘弹起..., Toast.LENTH_SHORT).show();
            //  ToastUtils.makeText("监听到软键盘弹起");
            isSoftshow = true;

        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {

            //  Toast.makeText(MainActivity.this, 监听到软件盘关闭..., Toast.LENGTH_SHORT).show();
            //ToastUtils.makeText("监听到软件盘关闭");
            isSoftshow = false;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shopCartGropCheckEvent(ShopCartGropCheckEvent shopCartGropCheckEvent) {
        //点击选择店铺
        int groupPosition = shopCartGropCheckEvent.getGroupPosition();
        boolean check = shopCartGropCheckEvent.isCheck();
        NofailureBean nofailureBean = mNofailureBeanList.get(groupPosition);
        nofailureBean.setCheck(check);
        List<CartBean> cart = nofailureBean.getCart();
        for (CartBean cartBean : cart) {
            cartBean.setIscheck(check);
        }
        setSelectAllState();
        mTvGoaccountActivityShopCar.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");

        mTvMoneyActivityShopCar.setText("￥" +UIUtils.getMoney( caculateSumPrice()));
        mShopCarAdapter.notifyDataSetChanged();
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ShopCartChildCheckEvent(ShopCartChildCheckEvent shopCartChildCheckEvent) {

        int groupPosition = shopCartChildCheckEvent.getGroupPosition();
        int childPosition = shopCartChildCheckEvent.getChildPosition();
        boolean check = shopCartChildCheckEvent.isCheck();
        NofailureBean nofailureBean = mNofailureBeanList.get(groupPosition);
        List<CartBean> cart = nofailureBean.getCart();
        cart.get(childPosition).setIscheck(check);
        //确定grop的状态
        for (int i = 0; i < cart.size(); i++) {
            CartBean cartBean = cart.get(i);
            if (!cartBean.isIscheck()) {
                nofailureBean.setCheck(false);
                break;
            } else {
                nofailureBean.setCheck(true);
            }

        }

        setSelectAllState();
        mTvGoaccountActivityShopCar.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
        mTvMoneyActivityShopCar.setText("￥" + UIUtils.getMoney(caculateSumPrice()));
        mShopCarAdapter.notifyDataSetChanged();


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ShopCartNumberEvent(ShopCartNumberEvent shopCartNumberEvent) {
        int number = shopCartNumberEvent.getNumber();
        final int childPosition = shopCartNumberEvent.getChildPosition();
        final int groupPosition = shopCartNumberEvent.getGroupPosition();
        int cartId = mNofailureBeanList.get(groupPosition).getCart().get(childPosition).getCartId();
        String gcs = "";

        for (NofailureBean nofailureBean : mNofailureBeanList) {

            for (CartBean cartBean : nofailureBean.getCart()) {

                if (cartBean.isIscheck()) {

                    gcs += cartBean.getCartId() + "_";
                }
            }
        }

        gcs = StringUtils.isEmpty(gcs) ? "-1" : gcs;

        if (!isSoftshow && number != 0) {

            Observable observable = ApiUtils.getApi().modifiyShopCartNumber(cartId, number, gcs).compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(Disposable disposable) throws Exception {

                    if (mLoadingDialog == null) {

                        mLoadingDialog = LoadingDialogUtils.createLoadingDialog(ShopCarActivity.this, "");
                    }
                    LoadingDialogUtils.show(mLoadingDialog);

                }
            }).subscribeOn(AndroidSchedulers.mainThread());


            HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<ModifyShopCartNumberBean>(this) {
                @Override
                protected void _onNext(StatusCode<ModifyShopCartNumberBean> modifyShopCartNumberBeanStatusCode) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                    ModifyShopCartNumberBean data = modifyShopCartNumberBeanStatusCode.getData();
                    String total_price = data.getTotal_price();
                    int count = data.getCount();
                    int code = data.getCode();
                    if (code == 100) {
                        //修改成功
                        mNofailureBeanList.get(groupPosition).getCart().get(childPosition).setCount(count);

                    } else if (code == 200) {
                        ToastUtils.makeText("库存不足");
                    }
                    mTvGoaccountActivityShopCar.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
                    mTvMoneyActivityShopCar.setText("￥" + UIUtils.getMoney(caculateSumPrice()));
                    mShopCarAdapter.notifyDataSetChanged();


                }

                @Override
                protected void _onError(String message) {
                    ToastUtils.makeText(message);
                    LoadingDialogUtils.closeDialog(mLoadingDialog);
                    mTvMoneyActivityShopCar.setText("￥" + UIUtils.getMoney(caculateSumPrice()));
                    mShopCarAdapter.notifyDataSetChanged();


                }
            }, "", lifecycleSubject, false, true);

        }


    }

    /**
     * 滑动删除
     * @param shopCartDeleteEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ShopCartDeleteEvent(ShopCartDeleteEvent shopCartDeleteEvent){
      //  ToastUtils.makeText("删除");
    final  ShopCarAdapter.ChildHold childHold = shopCartDeleteEvent.getChildHold();
        final int childPosition = shopCartDeleteEvent.getChildPosition();
        final int groupPosition = shopCartDeleteEvent.getGroupPosition();
        int cartId = mNofailureBeanList.get(groupPosition).getCart().get(childPosition).getCartId();
        Observable observable = ApiUtils.getApi().deleteShopCart(cartId+"").compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {

                if (mLoadingDialog == null) {

                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(ShopCarActivity.this, "");
                }
                LoadingDialogUtils.show(mLoadingDialog);

            }
        }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<String>(this) {
            @Override
            protected void _onNext(StatusCode<String> stringStatusCode) {


                LoadingDialogUtils.closeDialog(mLoadingDialog);

                childHold.swipemenulayout.quickClose();
                List<CartBean> cart = mNofailureBeanList.get(groupPosition).getCart();

                if (cart.size()==1){
                    mNofailureBeanList.remove(groupPosition);

                }else {
                mNofailureBeanList.get(groupPosition).getCart().remove(childPosition);
                }
                updateDateNumber();


                mShopCarAdapter.notifyDataSetChanged();

                if (mNofailureBeanList.size()==0 &&(mFailureBeans==null || mFailureBeans.size()==0)){

                    mLlNoDataActivityShopCar.setVisibility(View.VISIBLE);
                    mLlDataRootActicityShopCar.setVisibility(View.GONE);   //没数据

                 //   mTvTitle.setText("购物车(" + calulateShopNumber() + ")");

                }


            }
            @Override
            protected void _onError(String message) {

                ToastUtils.makeText(message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);

            }
        },"",lifecycleSubject,false,true);

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 计算总计
     *
     * @return
     */
    private double caculateSumPrice() {
        double sum = 0;
        for (NofailureBean nofailureBean : mNofailureBeanList) {

            for (CartBean cartBean : nofailureBean.getCart()) {

                if (cartBean.isIscheck()) {

                    if (cartBean.getDisprice() >0) {
                        sum += cartBean.getDisprice() * cartBean.getCount();
                    } else {
                        sum += cartBean.getPrice() * cartBean.getCount();

                    }

                }
            }
        }

        return sum;
    }

    /**
     * 计算购物车数量
     *
     * @return
     */
    private int calulateShopNumber() {
        int shopSum = 0;
        for (NofailureBean nofailureBean : mNofailureBeanList) {
            shopSum += nofailureBean.getCart().size();
        }

        return shopSum;
    }

    /**
     * 计算选中的数量
     *
     * @return
     */
    private int calulateSelecteNumber() {
        int selectNumber = 0;
        for (NofailureBean nofailureBean : mNofailureBeanList) {
            for (CartBean cartBean : nofailureBean.getCart()) {
                if (cartBean.isIscheck()) {
            selectNumber+=cartBean.getCount();
                }
            }
        }
        return selectNumber;
    }



    /**
     * 判断全选
     */
    private void setSelectAllState() {
        for (NofailureBean nofailureBean1 : mNofailureBeanList) {

            if (!nofailureBean1.isCheck()) {
                isAllSelect = false;
                break;
            } else {
                isAllSelect = true;

            }
        }


        if (isAllSelect) {
            mCbAllSelectActivityShopCar.setBackgroundResource(R.mipmap.chooce_green);
        } else {
            mCbAllSelectActivityShopCar.setBackgroundResource(R.mipmap.xe_h);

        }
    }

    /**
     * 更新数量
     */
    private void updateDateNumber(){

        mTvGoaccountActivityShopCar.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
        mTvMoneyActivityShopCar.setText("￥" + UIUtils.getMoney(caculateSumPrice()));
      //  mTvTitle.setText("购物车(" + calulateShopNumber() + ")");
        setSelectAllState();

        // calulateShopNumber()

    }




}
